#!/usr/bin/env python
#
# author windcao@hotmail.com
# Setup script for PIL 1.1.5 and later
#
# Usage: python png_resizer.py -f"icon.png" -c"genConf"
#
import sys
from PIL import Image
import getopt
from file_utils import *


def scale_icon(src_file_name, dst_file_name, dst_size):
    size_int = int(dst_size)

    print(
        f"scaling png image size from {src_file_name} to {dst_file_name} with size = {dst_size}")
    img = Image.open(os.path.abspath(src_file_name))
    img_tobe_scale = img.resize((size_int, size_int), Image.ANTIALIAS)
    img_tobe_scale.save(dst_file_name, 'PNG')


def quant_png(file_name):
    print(f"quanting png file : {file_name}")
    os.system(
        f"./pngquant/pngquant --quality=80-85 {file_name} --skip-if-larger -f")


def gen_png_by_cfg(src_file_dir, icon_size_cfg):

    dst_dir = ""
    file_to_process_list = []
    if os.path.isdir(src_file_dir):
        for parent, dirs, file_names in os.walk(src_file_dir):
            dst_dir = parent + "_mini_out"
            for size in icon_size_cfg:
                for filename in file_names:
                    if filename.endswith('.png'):
                        file_name, ext_name = os.path.splitext(filename)
                        dst_file_name = file_name + size + ext_name
                        file2optimize = os.path.join(parent, filename)
                        optimizefile = os.path.join(dst_dir, dst_file_name)
                        file_to_process_list.append(
                            (file2optimize, optimizefile, size))
    else:
        print(f"{src_file_dir} is not a dir")
        return

    for file_to_process, optimize_dst_file, scan_size in file_to_process_list:
        scale_icon(file_to_process, optimize_dst_file, scan_size)
        quant_png(optimize_dst_file)


def usage():
    print('png_resizer.py usage:')
    print('Gen icons with size in config')
    print('    python png_resizer.py -f"test.png"  -c"icon_size_list.cfg"')


def version():
    print('png_optimizer.py 1.0.0.0')


def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], 'hvf:c:',
                                   ['file=', 'icon_size_config='])
    except (getopt.GetoptError, err):
        print(str(err))
        usage()
        sys.exit(2)
    input_file = ''
    icon_size_cfg_list = []
    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(1)
        elif o in ('-v', '--version'):
            version()
            sys.exit(0)
        elif o in ('-f', '--file'):
            input_file = a
        elif o in ('-c', '--icon_size_config'):
            print(a)
            icon_size_cfg_list = read_lines(a)
        else:
            usage()
            sys.exit(3)
    if len(input_file) > 0 and len(icon_size_cfg_list) > 0:
        gen_png_by_cfg(input_file, icon_size_cfg_list)


if __name__ == '__main__':
    main(sys.argv)
